package com.pms.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.result.TableResultResponse;
import com.pms.rpc.UserService;
import com.pms.service.ICommunityService;
import com.pms.service.IWaterPumpHouseService;
import com.pms.utils.LBSUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lk
 * @since 2017-12-27
 */
@RestController
@RequestMapping("/pms/waterPumpHouse")
public class WaterPumpHouseController extends BaseController {
    @Autowired
    IWaterPumpHouseService waterPumpHouseService;
    @Autowired
    ICommunityService communityService;
    @Autowired
    UserService userService;
    @Autowired
    private LBSUtil lBSUtil;
    /**
     * 添加水泵房信息
     * @param
     * @return
     */
    @ApiOperation(value = "添加水泵房信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="所属小区id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="houseName",value="水泵房名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="houseRemark",value="水泵房备注信息",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name = "longitude", value = "经度值", required = true, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度值", required = true, dataType = "double", paramType = "form"),
    })
    public R add(Double longitude,Double latitude,Long communityId, String houseName, String houseRemark){
        parameterIsNull(communityId,"所属小区ID不能为空");
        parameterIsNull(houseName,"水泵房名称不能为空");
        if(longitude==null||latitude==null){
            return R.error(400,"水泵房地址信息不能为空");
        }
        Community community = communityService.selectOne(new EntityWrapper<Community>().eq("community_id",communityId));
        Assert.isNull(community,"对应的小区不存在");
        WaterPumpHouse waterPumpHouse = new WaterPumpHouse();
        waterPumpHouse.setCommunityId(communityId);
        waterPumpHouse.setHouseName(houseName);
        waterPumpHouse.setHouseRemark(houseRemark);
        waterPumpHouse.setHouseSort(waterPumpHouseService.selectMaxWaterPumpHouseSort(waterPumpHouse.getCommunityId())+1);
        waterPumpHouse.setWaterPumpHouseId(BaseModel.returnStaticIdLong());
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        lbsParamMap.put("ak", lBSUtil.getAK());
        lbsParamMap.put("geotable_id", lBSUtil.getWaterPumpHouseGeotableId());
        lbsParamMap.put("coord_type", 3);//坐标类型
        lbsParamMap.put("longitude", longitude);//经度
        lbsParamMap.put("latitude", latitude);//纬度
        lbsParamMap.put("address", community.getCommunityAddress());//地址
        lbsParamMap.put("title", houseName);//poi名称
        lbsParamMap.put("houseName", houseName);//poi名称
        lbsParamMap.put("communityId", communityId);//数据库社区id
        lbsParamMap.put("communityPoiId", community.getLbsPoiId());//数据库社区对应的lbsId
        JSONObject lbsJson = LBSUtil.poiCreateByMap(lbsParamMap);
        if (!lbsJson.getString("status").equals("0")) {
            logger.error("店铺LBS添加poi数据出错，返回信息:");
            logger.error(lbsJson.toString());
            return R.error("请求参数格式出错");
        }
        waterPumpHouse.setLbsPoiId(lbsJson.getString("id"));//设置Lbsid
        waterPumpHouse.setLatitude(latitude);
        waterPumpHouse.setLongitude(longitude);
        waterPumpHouseService.insert(waterPumpHouse);
        return R.ok();
    }

    /**
     * 删除水泵房信息
     * @param
     * @return
     */
    @ApiOperation(value = "删除水泵房信息")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="水泵房ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户ID",required = true,dataType = "Long",paramType="form")
    })
    public R delete(Long houseId,Long userId){
        parameterIsNull(houseId,"水泵房ID不能为空");
        parameterIsNull(userId,"用户ID不能为空");
        //查看会员权限，是否有删除的权限
        WaterPumpHouse waterPumpHouse = waterPumpHouseService.selectOne(new EntityWrapper<WaterPumpHouse>().eq("water_pump_house_id",houseId));
        Assert.parameterIsNull(waterPumpHouse,"没有对应的水泵房");
        waterPumpHouseService.deleteWaterPumpHouseAndWaterPump(houseId);//删除水泵房及下属的水泵
        if(!StringUtils.isEmpty(waterPumpHouse.getLbsPoiId())){
            Map<String, Object> lbsParamMap = new HashMap<String, Object>();
            lbsParamMap.put("ak", lBSUtil.getAK());
            lbsParamMap.put("geotable_id", lBSUtil.getWaterPumpHouseGeotableId());
            lbsParamMap.put("id",waterPumpHouse.getLbsPoiId());
            JSONObject lbsJson = LBSUtil.poiDeleteByMap(lbsParamMap);
        }
        return R.ok();
    }

    /**
     * 修改水泵房信息
     * @param
     * @return
     */
    @ApiOperation(value = "修改水泵房信息")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="水泵房ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="houseName",value="水泵房名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="houseRemark",value="备注信息",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name = "longitude", value = "经度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度值", required = false, dataType = "double", paramType = "form"),
    })
    public R update(Long houseId,Long userId,String houseName,String houseRemark,Double longitude,Double latitude){
        parameterIsNull(houseId,"水泵房ID不能为空");
        parameterIsNull(userId,"用户ID不能为空");
        //查看会员权限，是否有删除的权限
        WaterPumpHouse waterPumpHouse = waterPumpHouseService.selectOne(new EntityWrapper<WaterPumpHouse>().eq("water_pump_house_id",houseId));
        Assert.parameterIsNull(waterPumpHouse,"没有对应的水泵房");
        Community community = communityService.selectOne(new EntityWrapper<Community>().eq("community_id",waterPumpHouse.getCommunityId()));
        Assert.parameterIsNull(community,"该水泵房尚未绑定小区");
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        if(!StringUtils.isEmpty(houseName)){
            waterPumpHouse.setHouseName(houseName);
            lbsParamMap.put("houseName",houseName);
        }
        if(!StringUtils.isEmpty(houseRemark)){
            waterPumpHouse.setHouseRemark(houseRemark);
        }
        if(longitude!=null&&latitude!=null){
            waterPumpHouse.setLongitude(longitude);
            waterPumpHouse.setLatitude(latitude);
            lbsParamMap.put("longitude", longitude);//经度
            lbsParamMap.put("latitude", latitude);//纬度
            lbsParamMap.put("address", community.getCommunityAddress());//经度
        }
        waterPumpHouseService.updateById(waterPumpHouse);
        if(!lbsParamMap.isEmpty()&& !StringUtils.isEmpty(waterPumpHouse.getLbsPoiId())){
            lbsParamMap.put("ak", lBSUtil.getAK());
            lbsParamMap.put("geotable_id", lBSUtil.getWaterPumpHouseGeotableId());
            lbsParamMap.put("coord_type", 3);
            lbsParamMap.put("id", waterPumpHouse.getLbsPoiId());
            LBSUtil.poiUpdateByMap(lbsParamMap);
        }
        return R.ok();
    }

    /**
     * 查询水泵房信息
     * @param
     * @return
     */
    @ApiOperation(value = "查询水泵房信息")
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="水泵房ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户ID",required = true,dataType = "Long",paramType="form")
    })
    public R query(Long userId){
        parameterIsNull(userId,"用户ID不能为空");
        BaseUserInfo baseUserInfo = userService.getUserByUserId(userId);
        parameterIsNull(baseUserInfo,"没有此用户");
        Long companyId = baseUserInfo.getCompanyId();
        Long communityId = baseUserInfo.getCommunityId();
        Long areaId = baseUserInfo.getAreaId();
        Wrapper<WaterPumpHouse> wrapper = new EntityWrapper<WaterPumpHouse>();
        List<WaterPumpHouse> list = waterPumpHouseService.selectList(wrapper);
        return R.ok().put("list",list);
    }

    /**
     * 根据id查询水泵房信息
     * @param
     * @return
     */
    @ApiOperation(value = "根据id查询水泵房信息")
    @RequestMapping(value = "/queryById",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="水泵房ID",required = true,dataType = "Long",paramType="form")
    })
    public R queryById(Long houseId){
        parameterIsNull(houseId,"水泵房ID不能为空");
        Wrapper<WaterPumpHouse> wrapper = new EntityWrapper<WaterPumpHouse>();
        wrapper.eq("water_pump_house_id",houseId);
        WaterPumpHouse  waterPumpHouse = waterPumpHouseService.selectOne(wrapper);
        return R.ok().put("waterPumpHouse",waterPumpHouse);
    }

    /**
     * 分页查询
     * @param limit
     * @param page
     * @param houseName
     * @return
     */
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public TableResultResponse<WaterPumpHouse> page(Integer limit, Integer page, String houseName){
        if (limit==null){limit=10;}
            if (page==null){page=1;}
        Page<WaterPumpHouse> pages = new Page<WaterPumpHouse>(page,limit);
        pages = waterPumpHouseService.selectPage(pages,new EntityWrapper<WaterPumpHouse>().like("house_name",houseName));
        if (pages==null){
            return new TableResultResponse<WaterPumpHouse>();
        }else{
            return new TableResultResponse<WaterPumpHouse>(pages.getTotal(),pages.getRecords());
        }
    }


}
